<?php
namespace Verify;
use Verify\GeetestLib;

class Verify {
	/**
	 * 获取当前用户的临时id
	 * @return string 临时用户id
	 */
	public static function getUserId(){
		$userId = session('user_id');
		if(!$userId){
			$userId = uniqid(hash_hmac('md5', microtime(true), config('app.baseKey'), false), true);
			session('user_id', $userId);
		}
		return $userId;
	}

	/**
	 * 获取极验的code
	 * @return string code
	 */
	public static function getCode(){
		$config = config('app.geetest');
        $GtSdk = new GeetestLib($config['CAPTCHA_ID'], $config['PRIVATE_KEY']);
        $data = array(
            "user_id" => self::getUserId(),
            "client_type" => "web",
            "ip_address" => $_SERVER['REMOTE_ADDR'],
        );

        $status = $GtSdk->pre_process($data, 1);
        session('gtserver', $status);
        session('user_id', $data['user_id']);
        return $GtSdk->get_response_str();
	}

	/**
	 * 检查当前请求是否通过验证
	 * @return bool 验证结果
	 */
	public static function check(){
		if(!isset($_POST['geetest_challenge']) || !isset($_POST['geetest_validate']) || !isset($_POST['geetest_seccode'])){
			return false;
		}
		
		$config = config('app.geetest');
        $GtSdk = new GeetestLib($config['CAPTCHA_ID'], $config['PRIVATE_KEY']);
		$data = array(
            "user_id" => self::getUserId(),
            "client_type" => "web",
            "ip_address" => $_SERVER['REMOTE_ADDR'],
        );
		if(session('gtserver') == 1){ //服务器正常
			$result = $GtSdk->success_validate($_POST['geetest_challenge'], $_POST['geetest_validate'], $_POST['geetest_seccode'], $data);
			if($result){
				return true;
			} else {
				return false;
			}
		} else {  //服务器宕机,走failback模式
			if($GtSdk->fail_validate($_POST['geetest_challenge'], $_POST['geetest_validate'], $_POST['geetest_seccode'])) {
				return true;
			} else {
				return false;
			}
		}
	}
}